using System;
using System.Data;
using System.Text;
using System.Windows.Forms;

using ctsu.Data;

namespace ctsu.Admin.Forms
{

	public class FormReportProtocolActiveStatus : System.Windows.Forms.Form
	{
		private const string Active = "Active";
		private const string Inactive = "Expired";
		private const string Incomplete = "Incomplete";

		private DataTable _dtReport;
		private DataView _dvReport;

		#region windows controls
		private System.Windows.Forms.GroupBox gbxCriteria;
		private System.Windows.Forms.ComboBox cboStatus;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.DataGrid dg;
		private System.Windows.Forms.Button btnPrint;
		private System.Windows.Forms.Button btnExit;
		private System.Windows.Forms.Button btnRun;
		private Syncfusion.Windows.Forms.Tools.DateTimePickerAdv dtpDate;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox Count;
		private System.ComponentModel.Container components = null;
		#endregion windows controls

		public FormReportProtocolActiveStatus()
		{
			InitializeComponent();
			InitializeDataTable();
			this._dvReport = new DataView(this._dtReport);
			dg.DataSource = this._dvReport;
			InitializeGrid();
			cboStatus.SelectedIndex = 0;
			dtpDate.Value = DateTime.Today;
		}

		private void InitializeGrid()
		{
			//size grid columns				
			DataGridTableStyle dgts = new DataGridTableStyle();
			dgts.MappingName = "Report";
			dg.TableStyles.Add(dgts);

			for (int i = 0; i < this._dtReport.Columns.Count; i++)
			{
				dgts.GridColumnStyles[i].Width = (int)_dtReport.Columns[i].ExtendedProperties["Width"];
				dgts.GridColumnStyles[i].HeaderText = _dtReport.Columns[i].Caption;
			}
		}

		private void InitializeDataTable()
		{
			this._dtReport = new DataTable("Report");
			DataColumn dc = new DataColumn("ID", typeof(int));
			dc.Caption = "ID";
			dc.ExtendedProperties.Add("Width", 40);
			_dtReport.Columns.Add(dc);

			dc = new DataColumn("SPID", typeof(int));
			dc.Caption = "SPID";
			dc.ExtendedProperties.Add("Width", 40);
			_dtReport.Columns.Add(dc);

			dc = new DataColumn("ProtocolNumber", typeof(String));
			dc.Caption = "Protocol Number";
			dc.ExtendedProperties.Add("Width", 95);
			_dtReport.Columns.Add(dc);

			dc = new DataColumn("Expiration", typeof(String));
			dc.Caption = "Expiration";
			dc.ExtendedProperties.Add("Width", 75);
			_dtReport.Columns.Add(dc);

			dc = new DataColumn("Status", typeof(String));
			dc.Caption = "Status";
			dc.ExtendedProperties.Add("Width", 45);
			_dtReport.Columns.Add(dc);

			dc = new DataColumn("Remaining", typeof(int));
			dc.Caption = "Remain/Past";
			dc.ExtendedProperties.Add("Width", 80);
			_dtReport.Columns.Add(dc);
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code
		private void InitializeComponent()
		{
			this.gbxCriteria = new System.Windows.Forms.GroupBox();
			this.Count = new System.Windows.Forms.TextBox();
			this.label3 = new System.Windows.Forms.Label();
			this.btnRun = new System.Windows.Forms.Button();
			this.dtpDate = new Syncfusion.Windows.Forms.Tools.DateTimePickerAdv();
			this.label2 = new System.Windows.Forms.Label();
			this.label1 = new System.Windows.Forms.Label();
			this.cboStatus = new System.Windows.Forms.ComboBox();
			this.dg = new System.Windows.Forms.DataGrid();
			this.btnPrint = new System.Windows.Forms.Button();
			this.btnExit = new System.Windows.Forms.Button();
			this.gbxCriteria.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.dtpDate)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.dtpDate.Calendar)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.dg)).BeginInit();
			this.SuspendLayout();
			// 
			// gbxCriteria
			// 
			this.gbxCriteria.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.gbxCriteria.Controls.Add(this.Count);
			this.gbxCriteria.Controls.Add(this.label3);
			this.gbxCriteria.Controls.Add(this.btnRun);
			this.gbxCriteria.Controls.Add(this.dtpDate);
			this.gbxCriteria.Controls.Add(this.label2);
			this.gbxCriteria.Controls.Add(this.label1);
			this.gbxCriteria.Controls.Add(this.cboStatus);
			this.gbxCriteria.Location = new System.Drawing.Point(8, 0);
			this.gbxCriteria.Name = "gbxCriteria";
			this.gbxCriteria.Size = new System.Drawing.Size(744, 56);
			this.gbxCriteria.TabIndex = 0;
			this.gbxCriteria.TabStop = false;
			this.gbxCriteria.Text = "Criteria";
			// 
			// Count
			// 
			this.Count.Location = new System.Drawing.Point(496, 24);
			this.Count.Name = "Count";
			this.Count.ReadOnly = true;
			this.Count.Size = new System.Drawing.Size(40, 20);
			this.Count.TabIndex = 6;
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(456, 24);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(40, 16);
			this.label3.TabIndex = 5;
			this.label3.Text = "Count:";
			// 
			// btnRun
			// 
			this.btnRun.Location = new System.Drawing.Point(8, 24);
			this.btnRun.Name = "btnRun";
			this.btnRun.Size = new System.Drawing.Size(75, 23);
			this.btnRun.TabIndex = 4;
			this.btnRun.Text = "Run";
			this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
			// 
			// dtpDate
			// 
			this.dtpDate.BackgroundColor = new Syncfusion.Drawing.BrushInfo();
			this.dtpDate.Border3DStyle = System.Windows.Forms.Border3DStyle.Flat;
			this.dtpDate.BorderColor = System.Drawing.SystemColors.ControlDark;
			this.dtpDate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			// 
			// 
			// 
			this.dtpDate.Calendar.AllowMultipleSelection = false;
			this.dtpDate.Calendar.Culture = new System.Globalization.CultureInfo("");
			this.dtpDate.Calendar.DayNamesFont = new System.Drawing.Font("Verdana", 8F);
			this.dtpDate.Calendar.DaysFont = new System.Drawing.Font("Verdana", 8F);
			this.dtpDate.Calendar.DaysHeaderInterior = new Syncfusion.Drawing.BrushInfo(System.Drawing.SystemColors.Window);
			this.dtpDate.Calendar.Dock = System.Windows.Forms.DockStyle.Fill;
			this.dtpDate.Calendar.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.dtpDate.Calendar.GridLines = Syncfusion.Windows.Forms.Grid.GridBorderStyle.None;
			this.dtpDate.Calendar.HeaderHeight = 20;
			this.dtpDate.Calendar.HeaderStartColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(128)))), ((int)(((byte)(62)))));
			this.dtpDate.Calendar.Location = new System.Drawing.Point(0, 0);
			this.dtpDate.Calendar.MinValue = new System.DateTime(1753, 1, 1, 0, 0, 0, 0);
			this.dtpDate.Calendar.Name = "monthCalendar";
			// 
			// 
			// 
			this.dtpDate.Calendar.NoneButton.Location = new System.Drawing.Point(145, 0);
			this.dtpDate.Calendar.ScrollButtonSize = new System.Drawing.Size(24, 24);
			this.dtpDate.Calendar.SelectedDates = new System.DateTime[] {
        new System.DateTime(2004, 12, 17, 9, 3, 47, 453)};
			this.dtpDate.Calendar.Size = new System.Drawing.Size(217, 174);
			this.dtpDate.Calendar.SizeToFit = true;
			this.dtpDate.Calendar.Style = Syncfusion.Windows.Forms.VisualStyle.Office2003;
			this.dtpDate.Calendar.TabIndex = 0;
			// 
			// 
			// 
			this.dtpDate.Calendar.TodayButton.Location = new System.Drawing.Point(0, 0);
			this.dtpDate.Calendar.TodayButton.Size = new System.Drawing.Size(145, 20);
			this.dtpDate.Calendar.WeekFont = new System.Drawing.Font("Verdana", 8F);
			this.dtpDate.Calendar.WeekInterior = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.Color.PeachPuff, System.Drawing.Color.AntiqueWhite);
			this.dtpDate.DropDownImage = null;
			this.dtpDate.Format = System.Windows.Forms.DateTimePickerFormat.Short;
			this.dtpDate.Location = new System.Drawing.Point(344, 24);
			this.dtpDate.Name = "dtpDate";
			this.dtpDate.NullString = "";
			this.dtpDate.ShowCheckBox = false;
			this.dtpDate.Size = new System.Drawing.Size(88, 20);
			this.dtpDate.Style = Syncfusion.Windows.Forms.VisualStyle.Office2003;
			this.dtpDate.TabIndex = 3;
			this.dtpDate.Value = new System.DateTime(2004, 12, 17, 9, 3, 47, 453);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(280, 24);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(64, 16);
			this.label2.TabIndex = 2;
			this.label2.Text = "As of date:";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(96, 24);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(40, 16);
			this.label1.TabIndex = 1;
			this.label1.Text = "Status:";
			// 
			// cboStatus
			// 
			this.cboStatus.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this.cboStatus.Items.AddRange(new object[] {
            "Active",
            "Inactive",
            "Incomplete",
            "All"});
			this.cboStatus.Location = new System.Drawing.Point(144, 24);
			this.cboStatus.Name = "cboStatus";
			this.cboStatus.Size = new System.Drawing.Size(121, 21);
			this.cboStatus.TabIndex = 0;
			// 
			// dg
			// 
			this.dg.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
						| System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.dg.DataMember = "";
			this.dg.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dg.Location = new System.Drawing.Point(0, 64);
			this.dg.Name = "dg";
			this.dg.Size = new System.Drawing.Size(760, 416);
			this.dg.TabIndex = 1;
			// 
			// btnPrint
			// 
			this.btnPrint.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.btnPrint.Enabled = false;
			this.btnPrint.Location = new System.Drawing.Point(280, 488);
			this.btnPrint.Name = "btnPrint";
			this.btnPrint.Size = new System.Drawing.Size(75, 23);
			this.btnPrint.TabIndex = 2;
			this.btnPrint.Text = "Print";
			this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
			// 
			// btnExit
			// 
			this.btnExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.btnExit.Location = new System.Drawing.Point(368, 488);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(75, 23);
			this.btnExit.TabIndex = 3;
			this.btnExit.Text = "Exit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// FormReportProtocolActiveStatus
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(760, 518);
			this.Controls.Add(this.btnExit);
			this.Controls.Add(this.btnPrint);
			this.Controls.Add(this.dg);
			this.Controls.Add(this.gbxCriteria);
			this.Name = "FormReportProtocolActiveStatus";
			this.Text = "Protocol Active Status Report";
			this.gbxCriteria.ResumeLayout(false);
			this.gbxCriteria.PerformLayout();
			((System.ComponentModel.ISupportInitialize)(this.dtpDate.Calendar)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.dtpDate)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.dg)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		private void btnRun_Click(object sender, System.EventArgs e)
		{
			btnPrint.Enabled = false;
			int statusCriteria = cboStatus.SelectedIndex;
			StringBuilder sb = new StringBuilder();
			StringBuilder sbMessage = new StringBuilder();
			if (!VerifyCriteria(ref sbMessage))
			{
				MessageBox.Show(this, sbMessage.ToString(), "Enter All Criteria", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			}
			Cursor.Current = Cursors.WaitCursor;
			StringBuilder sql = new StringBuilder("SELECT ID, SPID, ProtocolNumber, IrbApproval, IrbRenewal, Incomplete FROM Protocol");

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			int id = 0;
			int spid = 0;
			string protoNum = "";
			DateTime dtApp = new DateTime(0);
			DateTime dtRen = new DateTime(0);
			bool incomplete = false;
			string status = "";
			int remaining = 0;
			string expiration = "";
			DataRow dr = null;

			this._dtReport.Clear();
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());
				while (reader.Read())
				{
					remaining = 0;
					expiration = "";

					id = reader.GetInt32(0);
					spid = reader.GetInt32(1);
					protoNum = reader.GetString(2);
					if (reader.IsDBNull(3))
						dtApp = new DateTime(0);
					else
						dtApp = reader.GetDateTime(3);
					if (reader.IsDBNull(4))
						dtRen = new DateTime(0);
					else
						dtRen = reader.GetDateTime(4);

					if (reader.IsDBNull(5))
						incomplete = false;
					else
						incomplete = reader.GetBoolean(5);

					if (incomplete)
						status = Incomplete;
					else
						status = CalculateStatus(dtApp, dtRen, out remaining, out expiration);

					dr = this._dtReport.NewRow();
					dr["ID"] = id;
					dr["SPID"] = spid;
					dr["ProtocolNumber"] = protoNum;
					dr["Expiration"] = expiration;
					dr["Status"] = status;
					dr["Remaining"] = remaining;

					switch (statusCriteria)
					{
						case 0://Active
							if (status != Active)
								continue;
							break;
						case 1://Inactive
							if (status != Inactive)
								continue;
							break;
						case 2://Incomplete
							if (status != Incomplete)
								continue;
							break;
					}
					this._dtReport.Rows.Add(dr);
				}
				dg.DataSource = null;
				this._dvReport = new DataView(this._dtReport);
				dg.DataSource = this._dvReport;
				Count.Text = this._dtReport.Rows.Count.ToString();
				if (this._dtReport.Rows.Count > 0)
					btnPrint.Enabled = true;
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve protocol info!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Retrieve Protocol Info Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private string CalculateStatus(DateTime dtApp, DateTime dtRen, out int remaining, out string expiration)
		{
			DateTime dtLatest;
			remaining = 0;
			expiration = "";

			if (dtApp.ToShortDateString() == "1/1/0101" && dtRen.ToShortDateString() == "1/1/0101")
			{
				return "   XXX";
			}

			if (dtApp.ToShortDateString() == "1/1/0101" || dtRen.ToShortDateString() == "1/1/0101")
			{
				if (dtApp.ToShortDateString() == "1/1/0101")
					dtLatest = dtRen;
				else
					dtLatest = dtApp;
			}
			else
			{
				dtLatest = dtApp;

				if (dtRen.CompareTo(dtApp) > 0)
					dtLatest = dtRen;
			}

			int addDays = 364;
			int year = dtLatest.Year;
			if (DateTime.IsLeapYear(year))
				addDays = 365;

			DateTime dtExp = dtLatest.AddDays(addDays);
			expiration = dtLatest.ToString("MM/dd/yyyy");

			TimeSpan ts = new TimeSpan(0);
			//compare to criteria date
			if (DateTime.Today.CompareTo(dtExp) > 0)
			{
				ts = DateTime.Today - dtExp;
				remaining = ts.Days;
				return Inactive;
			}

			ts = dtExp - DateTime.Today;
			remaining = ts.Days;
			return Active;
		}
		private bool VerifyCriteria(ref StringBuilder sbMessage)
		{
			//sbMessage.Append("");
			return true;
		}

		private void btnExit_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void btnPrint_Click(object sender, System.EventArgs e)
		{
			string criteria = "Criteria: Status = " + cboStatus.Text +
				"  As of date: " + dtpDate.Value.ToShortDateString() + "  Count: " + Count.Text;
			string[] title = new string[2];
			title[0] = "GCRC - Protocol Status Report";
			title[1] = criteria;
			DataView dv = (DataView)dg.DataSource;
			PrintingUtils pu = new PrintingUtils(dv, title, this, true);
			pu.Initialize();
		}

	}
}
